<!-- 头部公用 -->
<template>
  <div class="">
    <div class="headBack">
      <el-row class="container" style="max-width: 90%">
        <el-col :span="24">
          <!-- pc端导航 -->
          <div class="headBox">
            <el-menu :default-active="activeIndex"
                     class="el-menu-demo"
                     background-color="#545c64"
                     text-color="#fff"
                     active-text-color="#00bfff"
                     mode="horizontal"
                     :router="true">
              <el-menu-item index="/DashBoard"><i class="el-icon-s-home"></i> 首页</el-menu-item>
              <el-menu-item index="/announcement"><i class="el-icon-s-custom"></i>社区公告</el-menu-item>
              <el-submenu class="submenu" popper-class="submenu-class" index="/Dynamics">
                <template slot="title"><i class="fa fa-wa fa-archive"></i> 分类</template>
                <el-menu-item :key="'class1'" :index=" '/Dynamics?categoryId='+ '' " >全部</el-menu-item>
                <el-menu-item v-for="(item,index) in categoryList" :key="'category'+index" :index="'/Dynamics?categoryId='+item.id">{{item.name}}</el-menu-item>
              </el-submenu>
              <el-menu-item index="/Dynamics"><i class="el-icon-star-off"></i>社区动态</el-menu-item>
              <div class="search-class">
                <el-select
                  v-model="search"
                  remote
                  clearable
                  filterable
                  placeholder="请输入关键词"
                  :remote-method="remoteMethod"
                  @change="selectArticle"
                  :loading="loading"
                  class="search-select"
                >
                  <el-option
                    v-for="item in resultList"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div class="right-box">
                <div class="messageBox" v-if="userInfo">
                  <el-popover title="我的消息" trigger="hover" placement="bottom" width="300">
                    <div class="unread-container">
                      <span v-if="unreadContract.length <= 0">暂无消息</span>
                      <div title="旧梦一场" class="lemon-contact" v-for="item in unreadContract">
                        <span class="lemon-badge lemon-contact__avatar">
                          <span class="lemon-avatar" style="width: 40px; height: 40px; line-height: 40px; font-size: 20px;">
                            <img :src="item.avatar">
                          </span>
                          <span class="lemon-badge__label">{{item.unread}}</span>
                        </span>
                        <div class="lemon-contact__inner">
                          <p class="lemon-contact__label">
                            <span class="lemon-contact__name">{{item.displayName}}</span>
                            <span class="lemon-contact__time">{{item.lastSendTime}}</span>
                          </p>
                          <p class="lemon-contact__content">
                      <span>
                        {{item.lastContent}}
                      </span>
                          </p>
                        </div>
                      </div>
                    </div>
                    <div class="bell-container" slot="reference">
                      <el-badge :max="99" :value="unread" :hidden="unread <= 0">
                        <i class="el-icon-bell" />
                      </el-badge>
                    </div>
                  </el-popover>
                </div>
                <div class="mailBox" v-if="userInfo">
                  <el-popover title="我的代办(最近一周)" trigger="hover" placement="bottom" width="320"
                              :fallback-placements="['bottom', 'top', 'right', 'left']">
                    <div class="unread-container">
                      <span v-if="mailContent.length <= 0">暂无代办</span>
                      <el-row v-for="(mail, index) in mailContent" :key="index">
                        <el-badge is-dot :hidden="mail.readStatus === '1'" style="margin-top: 10px;margin-right: 3px;width: 98%">
                          <el-card :body-style="{ padding: '0px' }" shadow="hover" >
                            <div style="padding: 14px;">
                              <span class="span-class" >{{ mail.content }}</span>
                              <div style="margin-top: 5px">
                                <span class="time">{{ mail.createTime }}</span>
                                <el-button type="text"
                                           style="float: right;padding: 0;line-height: 12px;margin-right: 5px" @click="openMailDetail(mail)">查看详情</el-button>
                              </div>
                            </div>
                          </el-card>
                        </el-badge>
                      </el-row>
                    </div>
                    <div class="mail-container" slot="reference">
                      <el-badge :max="99" :value="mailUnread" :hidden="mailUnread <= 0" >
                        <i class="el-icon-s-promotion"/>
                      </el-badge>
                    </div>
                  </el-popover>
                </div>
                <div v-show="!haslogin" class="nologin">
                  <a href="javascript:void(0);" @click="logoinFun(1)">登录&nbsp;</a>|<a href="javascript:void(0);" @click="logoinFun(0)">&nbsp;注册</a>
                </div>
                <div v-show="haslogin" class="haslogin">
                  <i class="fa fa-fw fa-user-circle userImg"></i>
                  <ul class="haslogin-info">
                    <li>
                      <a href="#/UserInfo">个人中心</a>
                    </li>
                    <li>
                      <a href="javascript:void(0);" @click="userlogout">退出登录</a>
                    </li>
                  </ul>
                </div>
              </div>
            </el-menu>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog title="代办详情" :visible.sync="open" width="700px" top="50px" append-to-body @close="cancel">
      <div>
        <span style="display: block; font-size: 15px" v-html="detailMail.content.replace(/(\r\n|\n|\r)/gm, '<br />')"></span>
        <div style="float: right;display: block">{{ detailMail.createTime }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="check">已 阅</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {logout} from '../api/user'
  import {removeToken} from '../utils/auth'
  import {mapGetters} from "vuex";
  import {getTotalUnread, getUnreadContracts, listMailInfo, updateReadStatus} from "../api/websocket";
  import {getCategoryList} from "../api/category/category";
  import {getSearchArticle} from "../api/article/article";
  export default {
    name:'Nav',
    data() { //选项 / 数据
      return {
        userInfo: '', //用户信息
        haslogin: false, //是否已登录
        categoryList: '', //分类
        activeIndex: '/', //当前选择的路由模块
        state: '', //icon点击状态
        pMenu: true, //手机端菜单打开
        search: '',
        loading: false,
        resultList: [],
        // path:'',//当前打开页面的路径
        input: '', //input输入内容
        headBg: 'url(static/img/headbg05.jpg)', //头部背景图
        headTou: '', //头像
        projectList: '', //项目列表
        open: false,
        detailMail: {
          content: '',
          createTime: ''
        },
        hiddenProperty: undefined,
        visibilityChangeEvent: undefined
      }
    },
    computed: {
      ...mapGetters(['unread','unreadContract','mailUnread','mailContent'])
    },
    methods: {
      openMailDetail(mail) {
        this.detailMail = mail
        this.open = true
      },
      selectArticle(id) {
        this.search = ''
        if(this.$route.query.aid !== id){
          this.$router.push({name: 'ArticleDetail', query: {aid: id}})
        }
      },
      remoteMethod(query) {
        if(query !== '') {
          this.loading = true
          const queryParams = {
            search: query
          }
          getSearchArticle(queryParams).then((res) => {
            this.resultList = res
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        }
      },
      cancel() {
        this.open = false
      },
      check() {
        if(this.detailMail.readStatus === '0') {
          updateReadStatus(this.detailMail.hid).then((res) => {
            this.$store.dispatch('removeMailContent', this.detailMail)
            this.$message.success('操作成功')
            this.open = false
          })
        } else {
          this.open = false
        }
      },
      logoinFun: function(msg) { //用户登录和注册跳转
        // console.log(msg);
        localStorage.setItem('logUrl', this.$route.fullPath);
        // console.log(666,this.$router.currentRoute.fullPath);
        if (msg == 0) {
          this.$router.push({
            path: '/Login?login=0'
          });
        } else {
          this.$router.push({
            path: '/Login?login=1'
          });
        }
      },
      // 用户退出登录
      userlogout: function() {
        var that = this;
        this.$confirm('是否确认退出?', '退出提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // console.log(that.$route.path);

          logout().then((response)=>{
            removeToken()
            localStorage.removeItem('userInfo');
            this.$ws.$ws.close()
            that.haslogin = false;
            that.$message({
              type: 'success',
              message: '退出成功!'
            });
            that.$router.push({
              path: '/'
            });
          })
        }).catch(() => {
          //
        });

      },
      onVisibilityChange() {
        if (!document[this.hiddenProperty]) { //被隐藏
          if (localStorage.getItem('userInfo')) {
              this.haslogin = true;
            } else {
              this.haslogin = false;
            }
          }
      },
      routeChange: function() {
        var that = this;
        that.pMenu = true
        this.activeIndex = this.$route.path === '/' ? '/DashBoard' : this.$route.path;
        if (localStorage.getItem('userInfo')) { //存储用户信息
          that.haslogin = true;
          that.userInfo = JSON.parse(localStorage.getItem('userInfo'));
        } else {
          that.haslogin = false;
        }
      }
    },
    components: {

    },
    watch: {
      // 如果路由有变化，会再次执行该方法
      '$route': 'routeChange'
    },
    created() { //生命周期函数
       this.hiddenProperty = 'hidden' in document ? 'hidden' :
        'webkitHidden' in document ? 'webkitHidden' :
          'mozHidden' in document ? 'mozHidden' :
            null;
      this.visibilityChangeEvent = this.hiddenProperty.replace(/hidden/i, 'visibilitychange');
      document.addEventListener(this.visibilityChangeEvent, this.onVisibilityChange);
      // console.log();
      this.routeChange();

    },
    destroyed() {
      document.removeEventListener(this.visibilityChangeEvent, this.onVisibilityChange)
    },
    mounted() { //页面元素加载完成
      getCategoryList().then((res) => {
        this.categoryList = res
      })
      if(this.userInfo){
        getTotalUnread(this.userInfo.id).then((res) => {
          this.$store.dispatch('setUnread', res)
        })
        getUnreadContracts(this.userInfo.id).then((res) => {
          this.$store.dispatch('setUnreadContract', res)
        })
        listMailInfo(this.userInfo.id).then((res) => {
          this.$store.dispatch('setMailUnread', res.total)
          this.$store.dispatch('setMailContentList', res.rows)
        })
      }
    }
  }
</script>

<style>
  .el-menu--popup-bottom-start {
    margin-top: 0 !important;
  }
  .el-menu--popup {
    min-width: 150px !important;
  }
  .search-class {
    line-height: 45px;
    display: inline-block;
  }
  .search-select {
  }
  .el-select .el-input__inner {
    border-radius: 10px;
  }
  .submenu-class{
    max-height: 250px;
    overflow-x: hidden;
    overflow-y: scroll;
    margin-top: 5px;
    text-align: center;
    width: 150px;
    border-radius: 10px;
  }
  .submenu-class::-webkit-scrollbar {
    width: 4px;
  }
  .submenu-class::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: rgba(0,0,0,0.2);
  }
  .submenu-class::-webkit-scrollbar-track {
    border-radius: 0;
    background: rgba(0,0,0,0.1);
  }
  /*********头部导航栏********/
  .mail-container{
    position: relative;
    display: inline-block;
    height: 100%;
    line-height: 30px;
    font-size: 16px;
    cursor: pointer;
  }
  .bell-container{
    position: relative;
    display: inline-block;
    height: 100%;
    line-height: 30px;
    font-size: 16px;
    cursor: pointer;
  }
  /*头部导航栏盒子*/
  .mailBox {
    display: inline-block;
    margin-right: 15px;
  }
   .messageBox{
     display: inline-block;
     margin-right: 15px;
  }
  .haslogin-info {
    min-width: 60px;
    text-align: center;
  }
  .headBox .right-box {
    height: 100%;
    line-height: 45px;
    position: absolute;
    right: 0;
    top: 5px;
    color: #ffffff;
    font-size: 16px;
    display: inline-block;
  }
  .unread-container{
    overflow-y: auto;
    overflow-x: hidden;
    max-height: 350px;
  }
  .unread-container::-webkit-scrollbar {
    width: 4px;
  }
  .unread-container::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: rgba(0,0,0,0.2);
  }
  .unread-container::-webkit-scrollbar-track {
    border-radius: 0;
    background: rgba(0,0,0,0.1);
  }
  .max-h-300px {
    max-height: 300px;
  }
  .overflow-auto {
    overflow: auto;
  }
  .span-class {
    word-break: break-all;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
  }
  .time {
    color: #00bfff;
  }
  .button {
    padding: 0;
    float: right;
  }
  .headBack {
    width: 100%;
    height: 45px;
    background: #545c64;
    /*margin-bottom:30px;*/
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .12), 0 0 6px 0 rgba(0, 0, 0, .04);
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    z-index: 100;
  }

  .el-menu--horizontal>.el-submenu.is-active .el-submenu__title {
    border-bottom: none!important;
  }

  .headBox .el-menu {
    background: transparent;
    border-bottom: none!important;
  }

  .headBox .el-menu-demo li.el-menu-item,
  .headBox .el-menu--horizontal .el-submenu .el-submenu__title {
    height: 45px;
    line-height: 45px;
    border-bottom: none!important;

  }

  .headBox .el-submenu li.el-menu-item {
    height: 45px;
    line-height: 45px;
  }

  .headBox li .fa-wa {
    vertical-align: baseline;
  }

  .headBox .el-menu--horizontal .el-submenu>.el-menu {
    top: 45px;
    border: none;
    padding: 0;
  }
  .headBox>ul .el-submenu .el-menu .el-menu-item {
    min-width: 0;
  }

  .headBox .right-box a {
    color: #fff;
    font-size: 13px;
    transition: all 0.2s ease-out;
  }

  .headBox .right-box a:hover {
    color: #48456C;
  }

  .headBox .nologin {
    display: inline-block;
    text-align: right;
  }

  .headBox .haslogin {
    text-align: right;
    display: inline-block;
    position: relative;
    cursor: pointer;
  }

  .headBox .haslogin:hover ul {
    visibility: visible;
    opacity: 1;
  }

  .headBox .haslogin ul {
    background: rgba(40, 42, 44, 0.6);
    padding: 5px 10px;
    position: absolute;
    right: 0;
    visibility: hidden;
    opacity: 0;
    transition: all 0.3s ease-out;
  }

  .headBox .haslogin ul li {
    border-bottom: 1px solid #48456C;
  }

  .headBox .haslogin ul li:last-child {
    border-bottom: 1px solid transparent;
  }
</style>
